package cn.cj.erp.service;

import cn.cj.erp.bo.system.SysUserBo;
import cn.cj.erp.common.constants.BizCodeEnum;
import cn.cj.erp.common.http.Result;
import cn.cj.erp.common.utils.Assert;
import cn.cj.erp.common.vo.login.PasswordChangeVo;
import cn.cj.erp.common.vo.login.ProfileInfo;
import cn.cj.erp.service.system.SysUserService;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 个人信息业务处理
 *
 * @author jianchen
 */
@Service
public class SysProfileService {
    @Resource
    private SysUserService sysUserService;

    /**
     * 个人信息
     */
    public ProfileInfo profile(SysUserBo user) {
        String roleGroup = sysUserService.listUserRoleGroup(user.getUserId());
        return new ProfileInfo(user, roleGroup);
    }

    /**
     * 更新个人信息
     */
    public Result<Boolean> updateProfile(SysUserBo user) {
        //校验手机号
        boolean result = sysUserService.checkPhoneUnique(user);
        if (!result) {
            return Result.error(BizCodeEnum.EXIST_PHONE);
        }
        //校验邮箱
        result = sysUserService.checkEmailUnique(user);
        if (!result) {
            return Result.error(BizCodeEnum.EXIST_EMAIL);
        }
        //更新用户信息
        SysUserBo db = sysUserService.getById(user.getUserId());
        if (ObjectUtil.isNull(db)) {
            return Result.error("用户不存在");
        }
        user.setPassword(null);
        result = sysUserService.updateById(user);
        if (!result) {
            return Result.error(BizCodeEnum.FAIL_UPDATE);
        }
        return Result.ok(true);
    }

    /**
     * 修改登录用户密码
     */
    public boolean password(PasswordChangeVo vo) {
        // 解密密码
        vo.decrypt();
        Assert.strongPass(vo.getNewPassword(), "新密码必须包含数字、字母大小写、特殊字符，且超过8位");
        return sysUserService.updatePassword(vo.getUserId(), vo.getPassword(), vo.getNewPassword());
    }
}